<template lang="pug">
  .page
    .search-form.mb-15.pl-10.pr-10
      Row(type="flex" justify="start")
        template(v-if="status === 'employee'")
          Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
            span.label-txt.w80 姓名：
            Input(v-model="formData.employeeName" placeholder="请输入" clearable)
          Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
            span.label-txt.w80 身份证号码：
            Input(v-model="formData.idCardNo" placeholder="请输入" clearable)
          Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
            span.label-txt.w80 类型：
            Select(v-model="formData.category" clearable)
              Option(v-for="(item, index) of category_arr" :key="item.key" :value="item.key") {{item.value}}
          Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
            span.label-txt.w80 险种：
            Select(v-model="formData.InsuranceCode" clearable)
              Option(v-for="(item, index) of insuracetype_arr" :key="item.key" :value="item.key") {{item.value}}
        template(v-else)
          Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
            span.label-txt.w80 类型：
            Select(v-model="formData.InsuranceCode" clearable)
              Option(v-for="(item, index) of insuracetype_arr" :key="item.key" :value="item.key") {{item.value}}
        Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 12 }" :xxl="{span: 6}")
          span.label-txt.w80 参保编号：
          Input(v-model="formData.InsureNo" placeholder="请输入" clearable)
        Col.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 4}")
          Button(v-if="hasFind" type="info" @click="searchFn") 查询
    .lzw-section
      .tab-title
        .font-14(v-for="(item,index) in filterNav" :key="index" @click="filterMethod(index,$event)" :data-status="item.status" :class="tabIndex === index ? 'active' : ''") {{item.txt}}
      .tab-container
        .pl-20.pr-20
          Table.hasTitle-table.beautiful-table(width="100%" stripe :columns="thead" :data="listData" :loading="loading" @on-selection-change="tableSelectChange")
            ._table_header(slot="header")
              .table-title-lefttxt.pull-left
                |单位名称
                span.text-info.pl-5.pr-5.font-weight {{query.companyName}}
                Divider(type="vertical")
                |共
                span.text-info.pl-5.pr-5.font-weight {{totalcount}}
                |条
                Divider(type="vertical")
                |合计
                span.text-info.pl-5.pr-5.font-weight {{totalAmt}}
                |元
              .pull-right.table-title-btns
                Button.mybtn-2(v-if="hasDel" type="info" @click="batchDelBill").ml-15 删除
                Button.mybtn-2(v-if="hasExport" type="info" @click="exportFn").ml-15 导出
            template(slot-scope="{ row, index }" slot="action")
              Button.mr-10(type="text" size="small" @click="deleteBill(row.id)") 删除
            .clearfix.pl-20.pr-20(slot="footer")
              Page(:total="totalcount" :current="formData.pageIndex" :page-size="formData.pageSize" @on-change="pageChange" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
</template>

<script>
import HandleBillApi from './service.api.js'
import commonApi from '@/api/common.api.js'
import Mixin from './manualBill.thead.js'

export default {
  name: 'manual-bill',
  components: {
  },
  data () {
    return {
      tabIndex: 0,
      status: 'employee',
      loading: false,
      totalcount: 0,
      totalAmt: 0,
      pageIndex: 1,
      pageSize: 10,
      filterNav: [
        {
          txt: '明细账',
          status: 'employee'
        },
        {
          txt: '总账',
          status: 'customer'
        }
      ],
      category_arr: [],
      insuracetype_arr: [],
      ids: '',
      listData: [],
      thead: [],
      formData: {
        employeeName: '',
        idCardNo: '',
        category: '',
        insuracetype: '',
        InsureNo: '',
        pageIndex: 1,
        pageSize: 10
      },
    }
  },
  mixins: [Mixin],
  mounted () {
    this.setThead()
    this.getEnum()
  },
  computed: {
    query () {
      return this.$route.query
    },
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('HandleBillExport') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('HandleBillFind') > -1
    },
    // 删除
    hasDel () {
      return this.actionArr.indexOf('HandleBillDelete') > -1
    }
  },
  methods: {
    searchFn () {
      this.formData.pageIndex = 1
      this.setThead()
    },
    filterMethod (index,e) {
      this.tabIndex = index
      if (this.status === e.target.dataset.status) {
        return false
      } else {
        this.status = e.target.dataset.status
        this.formData = {
          employeeName: '',
          idCardNo: '',
          category: '',
          insuracetype: '',
          InsureNo: '',
          pageIndex: 1,
          pageSize: 10
        }
        this.setThead()
      }
    },
    // 获取明细列表
    getMingxiList () {
      this.loading = true
      HandleBillApi.getMingxiList(Object.assign(this.query,this.formData)).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.totalcount = res.data.totalRows
          this.totalAmt = res.data.totalAmt
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 获取总账列表
    getTotalList () {
      this.loading = true
      HandleBillApi.getTotalList(Object.assign(this.query,this.formData)).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.totalcount = res.data.totalRows
          this.totalAmt = res.data.totalAmt
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 设置表头
    setThead () {
      this.ids = ''
      let thead_extend = []
      if(this.status === 'employee') {
        thead_extend = ['selection', 'employeeName', 'idCardTypeName', 'idCardNo', 'categoryName_mx', 'insureNo', 'insuranceName', 'year', 'month', 'isPersonalBurden', 'baseAmt', 'rate', 'amt', 'action']
        this.thead = this.getTableColumns(thead_extend)
        this.getMingxiList()
      } else {
        thead_extend = ['selection', 'categoryName_zz', 'insureNo', 'amt', 'action']
        this.thead = this.getTableColumns(thead_extend)
        this.getTotalList()
      }
    },

    // 获取下拉
    async getEnum () {
      let groupNames = 'handlebill.category,handlebill.insuracetype'
      commonApi.getEnum({
        groupName: groupNames
      }).then((res) => {
        this.category_arr = this.getItems(res.data, 'handlebill.category')
        this.insuracetype_arr = this.getItems(res.data, 'handlebill.insuracetype')
      })
    },
    // 批量删除
    batchDelBill () {
      if (this.ids) {
        this.$Modal.confirm({
          title: '确认删除？',
          content: '<p>删除后不可撤销！</p>',
          loading: true,
          onOk: () => {
            if(this.status === 'employee') {
              this.delMingxiBill(this.ids)
            } else {
              this.delTotalBill(this.ids)
            }
          }
        })
      } else {
        this.$Message.warning("请先选择需要删除的条目！")
      }
    },

    // 删除
    deleteBill (id) {
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>删除后不可撤销！</p>',
        loading: true,
        onOk: () => {
          if(this.status === 'employee') {
            this.delMingxiBill(id)
          } else {
            this.delTotalBill(id)
          }
        }
      })
    },
    // 删除明细
    delMingxiBill (id) {
      HandleBillApi.delMingxiBill({
        id: id
      }).then(res => {
        this.$Modal.remove()
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getMingxiList()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 删除总账
    delTotalBill (id) {
      HandleBillApi.delTotalBill({
        id: id
      }).then(res => {
        this.$Modal.remove()
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getTotalList()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },

    // 导出
    exportFn () {
      if(this.status === 'employee') {
        this.exportMingxiBill(this.ids)
      } else {
        this.exportTotalBill(this.ids)
      }
    },
    exportMingxiBill (id) {
      HandleBillApi.exportMingxiBill(Object.assign({ids: id},this.query, this.formData)).then(res => {
        if (res.data.success) {
          if ('download' in document.createElement('a')) {
            const link = document.createElement('a')
            link.download = ''
            link.href = res.data.data
            link.click()
          }
          // this.$Message.success('成功')
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    exportTotalBill (id) {
      HandleBillApi.exportTotalBill(Object.assign({ids: id},this.query, this.formData)).then(res => {
        if (res.data.success) {
          if ('download' in document.createElement('a')) {
            const link = document.createElement('a')
            link.download = ''
            link.href = res.data.data
            link.click()
          }
          // this.$Message.success('成功')
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },
    
    tableSelectChange (val) {
      let arr = val.map(item => {
        return item.id
      })
      this.ids = arr.join(',')
    },
    pageChange (index) {
      this.formData.pageIndex = index
      this.setThead()
    },
    onpageSizeChange (val) {
      this.formData.pageIndex = 1
      this.formData.pageSize = val
      this.setThead()
    },
  }

}
</script>

<style lang="less">

</style>
